//
//  NetWorkTools.m
//  FSEDU
//
//  Created by 张帅 on 2018/6/23.
//  Copyright © 2018年 青岛广电传媒电子商务有限公司. All rights reserved.
//

#import "NetWorkTools.h"
#import "NetWorkCache.h"
#import "NetWorkReachability.h"
//#import "LoginViewController.h"
#define kUploadFile @""

@implementation NetWorkTools
static AFHTTPSessionManager *manager;

//网络单例
+ (AFHTTPSessionManager *)sharedHttpSession{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        manager = [AFHTTPSessionManager manager];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html",@"application/json;charset=UTF-8" ,nil];
        manager.requestSerializer.timeoutInterval = 10;

    });
//    登录成功功添加token 到 header 里
     NSString * token = [UserModel get_userModel].token;
    if ([token isHelpful]) {
        [manager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
        [manager.requestSerializer setValue:@"STUDENT" forHTTPHeaderField:@"TokenType"];
        [manager.requestSerializer setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    }
    return manager;
}


+ (void)jsonFormat_requestURLStr:(NSString *)urlStr params:(NSDictionary *)params success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure {
    AFHTTPSessionManager *manager = [NetWorkTools sharedHttpSession];
      if (![NetWorkReachability shareNetworkCenter].networkState) {
          if (failure) {
              NSError *error;
              failure(error);
          }
           [QMUITips hideAllTips];
           [QMUITips showError:@"网络已丢失"];
           return;
      }
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
   NSMutableURLRequest * request= [NetWorkTools setRequestURLString:urlStr JsonString:jsonString];
  NSURLSessionDataTask *task=  [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error==NO) {
            if (success) {
                success(responseObject);
            }
        } else {
            if (failure) {
                failure(error);
            }
        }
    }];
    [task resume];
}

+ (NSMutableURLRequest *)setRequestURLString:(NSString *)URLString JsonString:(NSString *)jsonString {
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:nil error:nil];
    request.timeoutInterval= 10;
    NSString * token = [UserModel get_userModel].token;
    if ([token isHelpful]) {//添加token
        [request setValue:token forHTTPHeaderField:@"Authorization"];
        [request setValue:@"STUDENT" forHTTPHeaderField:@"TokenType"];
    }
    [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    return request;
}


#pragma mark - 数据请求(不带缓存)
+(void)requestWithURLStr:(NSString *)urlStr method:(RequestMethod)method params:(NSDictionary *)params success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure{
    urlStr = [urlStr removeSpaceAndNewline:urlStr];
    [self requestWithURLStr:urlStr method:method params:params cache:nil success:success failure:failure];
}
#pragma mark - 数据请求(带缓存)
+ (void)requestWithURLStr:(NSString *)urlStr method:(RequestMethod)method params:(NSDictionary *)params cache:(HttpCacheBlock)cache success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure{
    GDLog(@"当前url %@",urlStr);
    //读取缓存
    NSString *pageS = [[NSString alloc] initWithFormat:@"%@",params[@"page"]];
    if([pageS isEqualToString:@"1"] || (params[@"page"] == nil)){
        id cacheObj = [NetWorkCache httpCacheForURL:urlStr parameters:params];
        if (cacheObj != nil && cache) {
            cache(cacheObj);
        }
    }
    AFHTTPSessionManager *manager = [NetWorkTools sharedHttpSession];
    if (![NetWorkReachability shareNetworkCenter].networkState) {
        if (failure) {
            NSError * error;
            failure(error);
        }
        [QMUITips hideAllTips];
         [QMUITips showError:@"网络已丢失"];
         return;
    }
       NSMutableDictionary *mudict = [NSMutableDictionary dictionaryWithDictionary:params];
     if (method == GET) {
         [manager GET:urlStr parameters:mudict headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             if (success){
                 [self dealSuccessWithUrl:urlStr params:params ResponeObject:responseObject cache:cache success:success failure:failure];
             }
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             if (failure) {
                 failure(error);
             }
         }];
     } else {
         [manager POST:urlStr parameters:mudict headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             [QMUITips hideAllTips];
             if (success){
                 [self dealSuccessWithUrl:urlStr params:params ResponeObject:responseObject cache:cache success:success failure:failure];
                }
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
               if (failure) {
                 failure(error);
             }
               [QMUITips hideAllTips];
         }];
     }
   

}

/**
 处理GET/POST请求到的数据
 
 @param urlStr urlStr URL路径
 @param params params 参数
 @param responseObject 请求到的数据
 @param cache 缓存
 @param success 成功回调
 @param failure 失败回调
 */
+(void)dealSuccessWithUrl:(NSString *)urlStr params:(NSDictionary *)params ResponeObject:(id)responseObject cache:(HttpCacheBlock)cache success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure{
    if ([responseObject isKindOfClass:[NSArray class]]) {//如果是数组时就崩溃了
        if (responseObject) {
            success(responseObject);
        }
        return;
    }
    NSDictionary * dic = responseObject;
//    if (params[kHiddenLoadingView] == nil) {
//        [self dismissLoading];
//    }
    
    if(dic.allKeys.count > 0){
        if (dic.allKeys.count > 0) {
            //数据正确返回
            if (cache) {
                //对数据进行异步缓存
                [NetWorkCache setHttpCache:responseObject URL:urlStr parameters:params];
            }
            if (responseObject) {
                success(responseObject);
            }
            else{
                //无data 提示msg
                if ([params[@"method"] isEqualToString:@"worker.isCertify"]) {//实名认证不需要提示
                    success(responseObject);
                }else{
//                    [self showErrorText:responseObject[@"msg"]];
                    success(responseObject);
                }
            }
        }
        else {
            NSString *errDesc = responseObject[@"message"];
            if (errDesc != nil) {
                NSLog(@"\n错误码:%@----错误描述:%@",responseObject[@"code"] , errDesc);
                if (failure) {
                    failure(responseObject[@"code"]);
                }
            }
        }
    }
}


/**
 错误码描述输出
 
 @param error NSError错误
 */
+(void)dealWithError:(NSError *)error{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NSErrorCodeDescipition.plist" ofType:nil];
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
    NSString *errorStr = dict[[NSString stringWithFormat:@"%ld",(long)error.code]] == nil ? @"未知错误" : dict[[NSString stringWithFormat:@"%ld",(long)error.code]];
    NSHTTPURLResponse *err = error.userInfo[@"com.alamofire.serialization.response.error.response"];
    NSString  *errDetail = [[NSString alloc] initWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] encoding:NSUTF8StringEncoding];
    NSInteger serverCode = err.statusCode;
//    GDLog(@"\n------------网络错误信息开始-----------\nURL:%@\n服务器错误码:%ld\n客户端错误码:%ld\n错误描述:%@ %@\n错误返回详细信息：%@\n------------网络错误信息结束-----------\n", error.userInfo[@"NSErrorFailingURLKey"],(long)serverCode,error.code,[NSHTTPURLResponse localizedStringForStatusCode:serverCode],errorStr,errDetail);
    //    [self showErrorText:@"服务器错误"];
    if(serverCode == 401){
//        [self dismissLoading];
//        [self showErrorText:@"用户身份过期，请重新登录"];
//        if([self.getViewController isKindOfClass:[LoginViewController class]]){
//            return;
//        }
//        [self presentLoginPage];
    }
}




#pragma mark 上传单张图片
+ (void)uploadImageWithImage:(UIImage *)image success:(UploadSuccessBlock)success failure:(HttpFailureBlock)failure progress:(ProgressBlock)progress {
    NSArray *array = [NSArray arrayWithObject:image];
    [self uploadWithPhotos:array success:success failure:failure progress:progress];
}

#pragma mark 上传多张图片
+ (void)uploadWithPhotos:(NSArray<UIImage *> *)photos  success:(UploadSuccessBlock)success failure:(HttpFailureBlock)failure progress:(ProgressBlock)progress{
    AFHTTPSessionManager *manager = [NetWorkTools sharedHttpSession];
    __block NSString *name = @"file";
    __block NSString *urlStr = upload_file_url;
    
    [manager POST:urlStr parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
         for (int i = 0; i < photos.count; i ++) {
            NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
            formatter.dateFormat=@"yyyyMMddHHmmss";
            NSString *str=[formatter stringFromDate:[NSDate date]];
            NSString *fileName=[NSString stringWithFormat:@"%@.jpg",str];
            UIImage *image = photos[i];

            NSData *imageData = UIImageJPEGRepresentation(image, 0.4);
            [formData appendPartWithFileData:imageData name:name fileName:fileName mimeType:@"image/jpeg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
         if (progress) {
            progress(uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([AppTools isStateSuccess:responseObject]) {
            NSDictionary * data =responseObject[@"data"];
            NSString * url =data[@"value"];
            if (success) {
                success(url);
            }
        } else {
            if (failure){
                failure(nil);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure){
            failure(error);
        }
        NSString *errorStr = [self errorDescribe:error];
        [QMUITips showError:errorStr];
    }];

//    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){
//        for (int i = 0; i < photos.count; i ++) {
//            NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
//            formatter.dateFormat=@"yyyyMMddHHmmss";
//            NSString *str=[formatter stringFromDate:[NSDate date]];
//            NSString *fileName=[NSString stringWithFormat:@"%@.jpg",str];
//            UIImage *image = photos[i];
//
//            NSData *imageData = UIImageJPEGRepresentation(image, 0.4);
//            [formData appendPartWithFileData:imageData name:name fileName:fileName mimeType:@"image/jpeg"];
//        }
//    } progress:^(NSProgress * _Nonnull uploadProgress) {
//        if (progress) {
//            progress(uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
//        }
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        if ([AppTools isStateSuccess:responseObject]) {
//            NSDictionary * data =responseObject[@"data"];
//            NSString * url =data[@"src"];
//            if (success) {
//                success(@"",url,@"");
//            }
//        }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        if (failure){
//            failure(error);
//        }
//        [self dealWithError:error];
//    }];
}


@end
